# -*- encoding: utf-8 -*-

"""
@File:      tc_libtalloc_libtalloc_func_003.py
@Time:      2024/04/07 14:33:20
@Author:    chenchunhu
@Version:   1.0
@Contact:   wb-cch358909@alibaba-inc.com
@License:   Mulan PSL v2
@Modify:    chenchunhu
"""

from common.basetest import LocalTest

class Test(LocalTest):
    """
    See tc_libtalloc_libtalloc_func_003.yaml for details

    :avocado: tags=P2,noarch,local,fix
    """

    PARAM_DIC = {"pkg_name": "libtalloc libtalloc-devel gcc"}
    def setUp(self):
        super().setUp(self.PARAM_DIC)
        cmdline = '''cat >talloc_test3.c<<"EOF"
#include <talloc.h>
#include <pthread.h>
#include <assert.h>
#include <stdio.h>

#define NUM_THREADS 5

void *thread_func(void *arg) {
    // 为每个线程创建一个独立的 talloc 上下文
    TALLOC_CTX *ctx = talloc_new(NULL);
    assert(ctx != NULL);
    
    // 在该线程上下文中创建对象
    int *obj = talloc_array(ctx, int, 256); // 假设为256个int
    assert(obj != NULL);

    // 做一些操作
    obj = talloc_realloc(ctx, obj, int, 512); // 重新分配为512个int
    assert(obj != NULL);

    // 释放上下文相关的所有内存块
    int blocks = talloc_free(ctx);
    assert(blocks == 0); // 应该没有泄漏的块

    return NULL;
}

int main() {
    pthread_t threads[NUM_THREADS];

    // 创建线程
    for (int i = 0; i < NUM_THREADS; i++) {
        int rc = pthread_create(&threads[i], NULL, thread_func, NULL);
        assert(rc == 0);
    }

    // 等待线程结束
    for (int i = 0; i < NUM_THREADS; i++) {
        pthread_join(threads[i], NULL);
    }

    printf("All threads have finished their work\\n");
    return 0;
}
EOF'''
        self.cmd(cmdline)

    def test(self):
        self.cmd("gcc -o talloc_test3 talloc_test3.c -ltalloc -lpthread")
        code, talloc_result = self.cmd("./talloc_test3")
        self.assertIn('All threads have finished their work', talloc_result)

    def tearDown(self):
        super().tearDown(self.PARAM_DIC)
        self.cmd("rm -rf talloc_test3.c talloc_test3")
